<?php
declare (strict_types=1);

namespace app\common\model;

class UserCollectBusiness extends Base
{
    protected $name = 'user_collect_business';

    public static function add($uid, $business_id): array
    {
        try {
            $business = Business::where(['id' => $business_id, 'is_del' => 0, 'status' => 1])->field('id,fans')->find();
            if (empty($business)) {
                return ['code' => -1, 'msg' => '店铺不存在'];
            }
            $info = parent::where(['uid' => $uid, 'business_id' => $business_id])->find();
            if ($info) {
                if ($info->is_del == 1) {
                    $info->create_time = time();
                    $info->is_del = 0;
                    $info->save();
                }
            } else {
                parent::create(['uid' => $uid, 'business_id' => $business_id]);
            }
            $business->fans = $business->fans + 1;
            $business->save();
            return ['code' => 1, 'msg' => '已关注'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function cancel($ids, $uid = ''): array
    {
        try {
            $expIds = explode(',', $ids);
            parent::update(['is_del' => 1], ['uid' => $uid, 'business_id' => $expIds]);

            Business::whereIn('id', $expIds)->where('fans', '>', 0)->dec('fans', 1)->update();

            return ['code' => 1, 'msg' => '已取消关注'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function isCollect($uid, $business_id): int
    {
        $count = parent::where(['uid' => $uid, 'business_id' => $business_id, 'is_del' => 0])->count();
        return $count ? 1 : 0;
    }
}
